<template>
  <div>
    <el-form ref="ruleFormRef" v-loading="loading" :model="ruleForm" status-icon :rules="rules" style="padding: 20px;" label-width="auto"
      class="demo-ruleForm">
     

      <el-row>
        <el-col :span="12">
          <el-form-item label="所属单位" prop="company_id">
            <el-tree-select v-model="ruleForm.company_id" :data="companyTree" placeholder="请选择所属单位" default-expand-all
              :props="{ label: 'name', value: 'id' }" check-strictly clearable filterable :disabled="disabled"
              :render-after-expand="false" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="role_ids">
            <el-select  v-model="ruleForm.role_ids" multiple placeholder="请选择所属角色" style="width: 100%" >
              <el-option v-for="item in roleData" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-form-item label="用户类型" prop="type">
            <el-radio-group v-model="ruleForm.type" size="small" :disabled="disabled">
              <el-radio v-for="item in proxy.$userTypeOptions" :value="item.value" size="small">{{ item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
      <el-row>
        <el-col :span="6">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="ruleForm.name" type="text" clearable placeholder="请输入真实姓名" autocomplete="off"
              :disabled="disabled" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="ruleForm.sex" size="small" :disabled="disabled">
              <el-radio v-for="item in proxy.$sexOptions" :value="item.value" size="small">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model="ruleForm.age" type="number" placeholder="请输入年龄" autocomplete="off"
              :disabled="disabled" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username" type="text" placeholder="请输入登录账号推荐手机号" autocomplete="off" :disabled="disabled" />
      </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="电话/账号" prop="phone">
            <el-input v-model="ruleForm.phone" type="text" clearable placeholder="请输入联系电话(即登录账号)" autocomplete="off"
              :disabled="disabled" />
          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="!disabled">
        <el-row>
          <el-col :span="12">
            <el-form-item label="登录密码" prop="password">
              <el-input v-model="ruleForm.password" type="password" clearable show-password placeholder="请输入登录密码"
                autocomplete="off" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="password_check">
              <el-input v-model="ruleForm.password_check" type="password" clearable show-password placeholder="请再次确认密码"
                autocomplete="off" :disabled="disabled" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-form-item label="状态" prop="status">
        <el-switch v-model="ruleForm.status" :active-value="1" active-text="启用" :inactive-value="2" inactive-text="禁用">
        </el-switch>

      </el-form-item>
      <el-form-item label="备注" prop="content">
        <el-input v-model="ruleForm.content" autosize :disabled="disabled" type="textarea" placeholder="请输入内容"
          autocomplete="off" />
      </el-form-item>
      <el-form-item v-if="props.type !== 'info'">
        <el-button size="large" type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
        <el-button size="large" @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, defineEmits, defineProps, getCurrentInstance } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRoute } from "vue-router";
import { companyApi } from '@/utils/api/company';
import { userApi } from '@/utils/api/admin';
import { ElMessage } from 'element-plus'
import { roleApi } from '@/utils/api/role';

const { proxy } = getCurrentInstance(); // 获取当前Vue实例的代理对象，用于访问全局属性。
const props = defineProps({
  id: Number,
  type: String
});
const disabled = ref(false)
if (props.type === 'info') {
  disabled.value = true
}


// 定义自定义事件
const emits = defineEmits(['close-dialog']);
// 使用 useRoute 获取参数
const route = useRoute();
let { params } = route
const loading = ref(false)


const convertToTree = (data: any[]): Tree[] => {
  const tree = [];
  const map = {};

  // 第一步：创建一个以 id 为键的映射表
  data.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  // 第二步：找出所有可能的父节点 id
  const allParentIds = new Set(data.map(item => item.pid));

  // 第三步：构建树形结构
  data.forEach(item => {
    if (!map[item.pid]) {
      // 如果该元素的 pid 不在 map 中，说明它没有父级，是根节点
      tree.push(map[item.id]);
    } else {
      // 否则，找到其父节点并将其添加到父节点的 children 数组中
      const parent = map[item.pid];
      if (parent) {
        parent.children.push(map[item.id]);
      }
    }
  });

  return tree;
}

// 获取个人信息
const getInfo = async (id: string) => {
  // 这里是获取个人信息的接口
  loading.value = true
  const res = await userApi.info({ id: id })
  loading.value = false
  Object.assign(ruleForm, res.data)
}

const companyTree = ref([])

const roleData = ref([])
const ruleFormRef = ref<FormInstance>()

interface IForm {
  id: string
  company_id: string
  role_ids: string[]
  name: string,
  phone: Number,
  age: Number,
  sex: Number,
  username: string,
  password: string,
  password_check: string,
  type: Number,
  image: string,
  content: string,
  status: Number,
}

const ruleForm = reactive<IForm>({
  id: null,
  company_id: null,
  role_ids:[],
  name: null,
  phone: null,
  age: null,
  sex: null,
  username: null,
  password: null,
  password_check: null,
  type: 0,
  image: null,
  content: null,
  status: 1,
})

const validatephone = (rule: any, value: any, callback: any) => {
  // 定义手机号码的正则表达式，这里以中国大陆手机号为例
  const regex = /^1[3-9]\d{9}$/;
  if (regex.test(value)) {
    callback()
  } else {
    callback(new Error('请输入有效的手机号码（即账号）'))
  }
}

const checkPassword = (passwordValue) => {
  // 定义正则表达式
  const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d{3})(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/;
  if (regex.test(passwordValue)) {
    return false
  } else {
    return '密码必须包含至少 1 个大写字母、1 个小写字母、3 位数字和 1 个特殊字符';
  }
};

const validatePassword = (rule: any, value: any, callback: any) => {
  if (ruleForm.id && !ruleForm.password && !ruleForm.password_check) {
    callback()
  } else {
    if (value === '') {
      callback(new Error('请输入登录密码'))
    } else {
      const result = checkPassword(value)
      if (result !== false) {
        callback(new Error(result))
      } else {
        if (ruleForm.password_check !== '') {
          if (!ruleFormRef.value) return
          ruleFormRef.value.validateField('password_check')
        }
        callback()
      }
    }
  }

}
const validatePasswordCheck = (rule: any, value: any, callback: any) => {
  if (ruleForm.id && !ruleForm.password && !ruleForm.password_check) {
    callback()
  } else {
    if (value === '') {
      callback(new Error('请再次确认登录密码'))
    } else if (value !== ruleForm.password) {
      callback(new Error("两次密码输入不一致!"))
    } else {
      callback()
    }
  }

}
const rules = reactive<FormRules<typeof ruleForm>>({
  name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
  phone: [{ validator: validatephone, trigger: 'blur' }],
  username: [{ validator: validatephone, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  password_check: [{ validator: validatePasswordCheck, trigger: 'blur' }],
  type: [{ required: true, message: '请选择用户类型', trigger: 'blur' }],
  // image: [{ required: true, message: '请上传头像', trigger: 'blur' }],

})

const submitForm = (formEl: FormInstance | undefined) => {

  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true
      if (ruleForm.id == null) {
        ruleForm.username = ruleForm.phone
        ruleForm.status = 1
        const postFormData = {...ruleForm}
          postFormData.password = btoa(ruleForm.password)
          postFormData.password_check = btoa(ruleForm.password_check)
        userApi.create(postFormData).then((res) => {
          loading.value = false
          if (res.code === 200) {
            emits('close-dialog');
            ElMessage({
              message: res.message,
              type: res.type,
            })
          } else {
            ElMessage({
              message: res.message,
              type: res.type,
            })
          }
        })
      } else {
        const postFormData = {...ruleForm}
        if(ruleForm.password){
          postFormData.password = btoa(ruleForm.password)
          postFormData.password_check = btoa(ruleForm.password_check)
        }
        userApi.update(postFormData).then((res) => {
          loading.value = false
          if (res.code === 200) {
            emits('close-dialog');
            ElMessage({
              message: res.message,
              type: res.type,
            })
          } else {
            ElMessage({
              message: res.message,
              type: res.type,
            })
          }
        })
      }

    } else {
      loading.value = false

    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(async () => {
  // 获取数据
  loading.value = true

  const res = await companyApi.getAll()
  companyTree.value = companyTree.value.concat(convertToTree(res.data))
  const res2 = await roleApi.getAll()
  roleData.value = res2.data
  if (props.id) {
    await getInfo(props.id)
  }
  loading.value = false


})
</script>

<style scoped>
.demo-ruleForm {
  background: #fff;
  margin-top: 10px;
}
</style>
